package com.ax.center.service.impl;

import com.ax.center.dto.ApiResponse;
import com.ax.center.entity.RoleAuth;
import com.ax.center.mapper.RoleAuthMapper;
import com.ax.center.service.RoleAuthService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthMapper,RoleAuth> implements RoleAuthService {
    private final RoleAuthMapper roleAuthMapper;

    @Autowired
    public RoleAuthServiceImpl(RoleAuthMapper roleAuthMapper) {
        this.roleAuthMapper = roleAuthMapper;
    }

    @Override
    public ApiResponse queryAuthByRoleId(Long roleId) {
        List<RoleAuth> roleAuthList = query().eq("role_id", roleId).list();
         return ApiResponse.ok(roleAuthList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse insertMore(Long id, List<Long> permissions) {

            for (Long permissionId : permissions) {
                RoleAuth roleAuth = new RoleAuth();
                roleAuth.setRoleId(id);
                roleAuth.setAuthorityId(permissionId);
                roleAuthMapper.insert(roleAuth);
            }
            return  ApiResponse.ok("插入成功");
    }

    @Override
    public ApiResponse insertOne(Long id, Long authId) {
        if (query().eq("role_id",id).eq("auth_id",authId).count()>0) {
            return ApiResponse.fail("该权限已存在");
        }
        RoleAuth roleAuth = new RoleAuth();
        roleAuth.setRoleId(id);
        roleAuth.setAuthorityId(authId);
        boolean save = save(roleAuth);
        if (Boolean.TRUE==save) {
            return ApiResponse.ok("添加成功");
        }else {
            return ApiResponse.fail("添加失败");
        }
    }

    @Override
    public ApiResponse deleteOneByRoleId(Long roleId) {
        QueryWrapper<RoleAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);

        // 执行删除操作
        boolean deletionSuccessful = roleAuthMapper.delete(queryWrapper) > 0;
        if (deletionSuccessful) {
            return ApiResponse.ok("删除成功");
        } else {
            return ApiResponse.fail("删除失败");
        }
    }





}
